﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Activation;
using Ashlen.Portal.Core;
using Ashlen.Portal.Core.DTO;
using Ashlen.Portal.Core.DataInterfaces;
using Ashlen.Portal.Data.SqlServer;
using System.Web.Mvc;
using System.Web.Caching;
using System.Web;

namespace Ashlen.Portal.Services
{
    /// <summary>
    /// The NewsService service contains news related functionality. It contains News business logic and instantiates the 
    /// INewsDao object to interact with the database.
    /// </summary>
    /// <author>Shailen Sukul</author>
    /// <date>08 Nov 2006</date>
    /// <remarks>- JSON cannot understand LINQ-ENTITY objects (recursion problem while serializing) so had to have the methods returning anonymous type.
    /// This returns a much simpler object for ex: Select(f => new { f.Id, f.Caption ...} in the Dao layer.
    /// The return is a string type, which is actually JSON formatted as string. Look at the Ashlen.Portal.Core.Service.ServiceResponse object to learn about
    /// the response type.
    /// The decision to use JSON over XML was purely for performance reasons (JSON has a much smaller footprint).
    /// </remarks>
    public class WidgetService : IWidgetService
    {
        private IWidgetDao _widgetDao;
        public WidgetService()
        {
            _widgetDao = new WidgetDao();
        }

        /// <summary>
        /// Load all widgets in a list
        /// </summary>
        /// <returns></returns>
        public string LoadWidgets() {
            ServiceResponse response = new ServiceResponse();
            try {
                OutgoingWebResponseContext Response = WebOperationContext.Current.OutgoingResponse;
                HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl;
                String cacheControlValue = String.Format("max-age={0}, must-revalidate", 1);
                Response.Headers.Add(cacheHeader, cacheControlValue);
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";

                var widgets = _widgetDao.SelectWidgets();
                response.IsSuccess = true;
                response.Payload = widgets;
            }
            catch (Exception ex) {
                response = Utility.GetErrorResponse(ex);
            }
            return Newtonsoft.Json.JavaScriptConvert.SerializeObject(response);
        }

        /// <summary>
        /// Creates a widget
        /// </summary>
        /// <returns></returns>
        public string CreateWidget(string name, string url, string desc, int version, string author, bool isDefault, 
                                string body, string defaultState, string icon, int orderNo, string userCreated)
        {
            ServiceResponse response = new ServiceResponse();
            try {
                OutgoingWebResponseContext Response = WebOperationContext.Current.OutgoingResponse;
                HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl;
                String cacheControlValue = String.Format("max-age={0}, must-revalidate", 1);
                Response.Headers.Add(cacheHeader, cacheControlValue);
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";

                Guid id = _widgetDao.CreateWidget(name, url, desc, version, author, isDefault, body,
                    defaultState, icon, orderNo, userCreated);
                response.IsSuccess = true;
                response.Payload = id;
            }
            catch (Exception ex) {
                response = Utility.GetErrorResponse(ex);
            }
            return Newtonsoft.Json.JavaScriptConvert.SerializeObject(response);
        }

        /// <summary>
        /// Creates a widget
        /// </summary>
        /// <returns></returns>
        public string SelectWidget(Guid? id, string name) {
            ServiceResponse response = new ServiceResponse();
            try {
                OutgoingWebResponseContext Response = WebOperationContext.Current.OutgoingResponse;
                HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl;
                String cacheControlValue = String.Format("max-age={0}, must-revalidate", 1);
                Response.Headers.Add(cacheHeader, cacheControlValue);
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";

                ui_Widget widget = _widgetDao.SelectWidget(id, name) as ui_Widget;
                response.IsSuccess = true;
                var widgetJSON = new { widget.ID, widget.Name, widget.OrderNo, widget.IsDefault, widget.Icon, widget.Author,
                                       widget.Body,
                                       widget.DateCreated,
                                       widget.DateUpdated,
                                       widget.DefaultState,
                                       widget.Description,
                                       widget.Timestamp,
                                       widget.Url,
                                       widget.UserCreated,
                                       widget.UserUpdated,
                                       widget.VersionNo,
                };
                response.Payload = widgetJSON;
            }
            catch (Exception ex) {
                response = Utility.GetErrorResponse(ex);
            }
            return Newtonsoft.Json.JavaScriptConvert.SerializeObject(response);
        }

        public string SelectPages(string username) {
            ServiceResponse response = new ServiceResponse();
            try {
                OutgoingWebResponseContext Response = WebOperationContext.Current.OutgoingResponse;
                HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl;
                String cacheControlValue = String.Format("max-age={0}, must-revalidate", 1);
                Response.Headers.Add(cacheHeader, cacheControlValue);
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";

                List<ui_Page> pages = _widgetDao.SelectPages(username) as List<ui_Page>;
                response.IsSuccess = true;
                var pagesJSON = new ArrayList();
                if (pages != null) {
                    foreach (ui_Page page in pages) {
                        pagesJSON.Add(new {
                            page.ID,
                            page.DateCreated,
                            page.DateUpdated,
                            /*page.ui_Layout.Name,*/
                            string.Empty,
                            page.Title,
                            page.UserCreated,
                            page.UserId,
                            page.UserUpdated,
                            page.VersionNo,
                            /* Layout = new {
                                page.ui_Layout.Id,
                                page.ui_Layout.Name,
                                page.ui_Layout.Description
                            }*/
                            Blah=string.Empty
                        });
                    }
                }
                response.Payload = pagesJSON;
            }
            catch (Exception ex) {
                response = Utility.GetErrorResponse(ex);
            }
            return Newtonsoft.Json.JavaScriptConvert.SerializeObject(response);
        }

        public string SelectWidgets(string pageId) {
            ServiceResponse response = new ServiceResponse();
            try {
                OutgoingWebResponseContext Response = WebOperationContext.Current.OutgoingResponse;
                HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl;
                String cacheControlValue = String.Format("max-age={0}, must-revalidate", 1);
                Response.Headers.Add(cacheHeader, cacheControlValue);
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";

                List<ui_WidgetInstance> widgets = _widgetDao.SelectWidgets(new Guid(pageId)) as List<ui_WidgetInstance>;
                response.IsSuccess = true;
                var widgetsJSON = new ArrayList();
                foreach (ui_WidgetInstance wi in widgets) {
                    var widget = new {
                        wi.Id,
                        wi.ColumnNo,
                        wi.DateCreated,
                        wi.DateUpdated,
                        wi.Expanded,
                        wi.OrderNo,
                        wi.State,
                        wi.Title,
                        wi.UserCreated,
                        wi.UserUpdated,
                        wi.VersionNo,
                        Widget = new {
                            wi.ui_Widget.ID,
                            wi.ui_Widget.Author,
                            wi.ui_Widget.Body,
                            wi.ui_Widget.DateCreated,
                            wi.ui_Widget.DateUpdated,
                            wi.ui_Widget.DefaultState,
                            wi.ui_Widget.Description,
                            wi.ui_Widget.Name,
                            wi.ui_Widget.Url,
                            wi.ui_Widget.UserCreated,
                            wi.ui_Widget.UserUpdated,
                            wi.ui_Widget.VersionNo
                        }
                    };
                    widgetsJSON.Add(widget);
                }
                
                response.Payload = widgetsJSON;
            }
            catch (Exception ex) {
                response = Utility.GetErrorResponse(ex);
            }
            return Newtonsoft.Json.JavaScriptConvert.SerializeObject(response);
        }

        public string SelectPage(string title, string username) {
            ServiceResponse response = new ServiceResponse();
            try {
                OutgoingWebResponseContext Response = WebOperationContext.Current.OutgoingResponse;
                HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl;
                String cacheControlValue = String.Format("max-age={0}, must-revalidate", 1);
                Response.Headers.Add(cacheHeader, cacheControlValue);
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";

                ui_Page widget = _widgetDao.SelectPage(title, username) as ui_Page;
                response.IsSuccess = true;
                var widgetJSON = new {
                    widget.ID,
                    widget.DateCreated,
                    widget.DateUpdated,
                    /* widget.ui_Layout.Name, */
                    string.Empty,
                    widget.Title,
                    widget.UserCreated,
                    widget.UserId,
                    widget.UserUpdated,
                    widget.VersionNo
                };
                response.Payload = widgetJSON;
            }
            catch (Exception ex) {
                response = Utility.GetErrorResponse(ex);
            }
            return Newtonsoft.Json.JavaScriptConvert.SerializeObject(response);
        }

        public string CreatePage(string title, string username, int layoutType) {
            ServiceResponse response = new ServiceResponse();
            try {
                OutgoingWebResponseContext Response = WebOperationContext.Current.OutgoingResponse;
                HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl;
                String cacheControlValue = String.Format("max-age={0}, must-revalidate", 1);
                Response.Headers.Add(cacheHeader, cacheControlValue);
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";

                ui_Page page = _widgetDao.CreatePage(title, username, 1, layoutType, username) as ui_Page;
                response.IsSuccess = true;
                var widgetJSON = new {
                    page.ID,
                    page.DateCreated,
                    page.DateUpdated,
                    page.Title,
                    page.Timestamp,
                    Blah=string.Empty,
                    /* Layout = new { page.ui_Layout.Id, page.ui_Layout.Name }, */
                    page.UserCreated,
                    page.UserId,
                    page.UserUpdated,
                    page.VersionNo
                };
                response.Payload = widgetJSON;
            }
            catch (Exception ex) {
                response = Utility.GetErrorResponse(ex);
            }
            return Newtonsoft.Json.JavaScriptConvert.SerializeObject(response);
        }

        public string DeletePage(string pageId) {
            ServiceResponse response = new ServiceResponse();
            try {
                OutgoingWebResponseContext Response = WebOperationContext.Current.OutgoingResponse;
                HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl;
                String cacheControlValue = String.Format("max-age={0}, must-revalidate", 1);
                Response.Headers.Add(cacheHeader, cacheControlValue);
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";

                _widgetDao.DeletePage(new Guid(pageId));
                response.IsSuccess = true;
            }
            catch (Exception ex) {
                response = Utility.GetErrorResponse(ex);
            }
            return Newtonsoft.Json.JavaScriptConvert.SerializeObject(response);
        }

        public string EditPage(string pageId, string title, string username, string layoutId) {
            ServiceResponse response = new ServiceResponse();
            try {
                OutgoingWebResponseContext Response = WebOperationContext.Current.OutgoingResponse;
                HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl;
                String cacheControlValue = String.Format("max-age={0}, must-revalidate", 1);
                Response.Headers.Add(cacheHeader, cacheControlValue);
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";

                _widgetDao.UpdatePage(new Guid(pageId), title, username, Convert.ToInt32(layoutId));
                response.IsSuccess = true;
            }
            catch (Exception ex) {
                response = Utility.GetErrorResponse(ex);
            }
            return Newtonsoft.Json.JavaScriptConvert.SerializeObject(response);
        }
    }
}
